package com.soft.base.mybatis.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.soft.base.mybatis.type.ListLong;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
@MappedTypes({ListLong.class})
public class ListLongTypeHandler implements TypeHandler<ListLong> {
    @Override
    public void setParameter(PreparedStatement ps, int i, ListLong parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, null);
            return;
        }
        String json = JSON.toJSONString(parameter);
        ps.setString(i, json);
    }

    @Override
    public ListLong getResult(ResultSet rs, String columnName) throws SQLException {
        ListLong ret = JSONArray.parseObject(rs.getString(columnName), ListLong.class);
        if (null == ret) {
            ret = new ListLong();
        }
        return ret;
    }

    @Override
    public ListLong getResult(ResultSet rs, int columnIndex) throws SQLException {
        ListLong ret = JSONArray.parseObject(rs.getString(columnIndex), ListLong.class);
        if (null == ret) {
            ret = new ListLong();
        }
        return ret;
    }

    @Override
    public ListLong getResult(CallableStatement cs, int columnIndex) throws SQLException {
        ListLong ret = JSONArray.parseObject(cs.getString(columnIndex), ListLong.class);
        if (null == ret) {
            ret = new ListLong();
        }
        return ret;
    }
}
